package com.organize.application.services.impl;

import com.autumn.exception.ExceptionUtils;
import com.autumn.mybatis.wrapper.EntityQueryWrapper;
import com.autumn.zero.common.library.application.services.common.AbstractTreeAppService;
import com.organize.application.dto.department.DepartmentInput;
import com.organize.application.dto.department.DepartmentOutput;
import com.organize.application.services.DepartmentAppService;
import com.organize.entities.Department;
import com.organize.entities.Employee;
import com.organize.repositories.DepartmentRepository;
import com.organize.repositories.EmployeeRepository;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * 部门管理
 * <p>
 * </p>
 *
 * @description TODO
 * @author: 老码农
 * @create: 2020-10-17 15:04
 **/
public class DepartmentAppServiceImpl extends AbstractTreeAppService<Department,
        DepartmentRepository,
        Department,
        DepartmentRepository,
        DepartmentInput, DepartmentOutput, DepartmentOutput> implements DepartmentAppService {

    @Autowired
    private EmployeeRepository employeeRepository;

    @Override
    public String getModuleName() {
        return "部门管理";
    }

    @Override
    protected void deleteBefore(Department entity) {
        EntityQueryWrapper<Employee> wrapper = new EntityQueryWrapper<Employee>(Employee.class);
        wrapper.where().eq(Employee.FIELD_DEPARTMENT_ID, entity.getId())
                .of()
                .lockByUpdate();
        if (this.employeeRepository.countByWhere(wrapper) > 0) {
            ExceptionUtils.throwValidationException("已被职员引用，不能删除。");
        }
        super.deleteBefore(entity);
    }

    @Override
    public boolean isEnableCache() {
        return super.isEnableCache();
    }
}
